<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>儿童绘画板</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        :root {
            --primary-color: #4e73df;
            --secondary-color: #f8f9fc;
            --dark-color: #5a5c69;
            --light-color: #ffffff;
        }

        html,
        body {
            margin: 0;
            padding: 0;
            height: 100vh;
            width: 100vw;
            overflow: hidden;
            font-family: 'Comic Sans MS', 'Marker Felt', 'Arial Rounded MT Bold', sans-serif;
            background-color: #f8f9fc;
            touch-action: none;
            /* Prevent default touch behaviors */
        }

        body {
            display: flex;
            flex-direction: column;
        }

        .header {
            background-color: var(--primary-color);
            color: white;
            padding: 8px 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            z-index: 1000;
        }

        .title {
            font-size: 1.5rem;
            font-weight: bold;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
        }

        .toolbar {
            background-color: var(--light-color);
            padding: 8px;
            display: flex;
            flex-wrap: nowrap;
            overflow-x: auto;
            gap: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            z-index: 999;
            -webkit-overflow-scrolling: touch;
            /* Smooth scrolling on iOS */
        }

        .btn-tool {
            width: 48px;
            height: 48px;
            border-radius: 8px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            font-size: 1rem;
            border: 2px solid transparent;
            background-color: #fff;
            transition: all 0.2s ease;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
            flex-shrink: 0;
            touch-action: manipulation;
            /* Prevent double-tap zoom */
        }

        .btn-tool:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        .btn-tool.active {
            border-color: var(--primary-color);
            background-color: rgba(78, 115, 223, 0.2);
            transform: translateY(-2px);
        }

        .btn-tool i {
            font-size: 1.4rem;
        }

        .btn-tool-label {
            font-size: 0.7rem;
            margin-top: 2px;
            display: none;
            /* Hide labels on mobile */
        }

        .color-picker {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            border: 2px solid white;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
            cursor: pointer;
            transition: all 0.2s ease;
            flex-shrink: 0;
        }

        .color-picker:hover {
            transform: scale(1.1);
        }

        .color-picker.active {
            transform: scale(1.15);
            box-shadow: 0 0 12px rgba(0, 0, 0, 0.3);
        }

        .color-palette {
            display: flex;
            gap: 8px;
            align-items: center;
            padding: 6px 8px;
            background-color: white;
            border-radius: 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
            flex-shrink: 0;
        }

        .canvas-container {
            flex-grow: 1;
            overflow: hidden;
            position: relative;
            background-color: #e9ecef;
            touch-action: none;
        }

        #drawing-canvas,
        #preview-canvas {
            position: absolute;
            top: 0;
            left: 0;
            cursor: crosshair;
            transform-origin: center center;
            width: 100%;
            height: 100%;
        }

        #preview-canvas {
            pointer-events: none;
            opacity: 0.7;
        }

        .zoom-controls {
            position: absolute;
            bottom: 16px;
            right: 16px;
            display: flex;
            flex-direction: column;
            gap: 8px;
            z-index: 100;
        }

        .zoom-btn {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 3px 8px rgba(0, 0, 0, 0.2);
            cursor: pointer;
            font-size: 1.2rem;
            border: none;
            transition: all 0.2s ease;
        }

        .zoom-btn:hover {
            background-color: #f5f5f5;
            transform: scale(1.05);
        }

        .brush-size-preview {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            background-color: black;
            margin: 0 auto;
            transition: all 0.2s ease;
        }

        .brush-size-control {
            display: flex;
            align-items: center;
            gap: 8px;
            flex-shrink: 0;
        }

        input[type="range"] {
            width: 80px;
            accent-color: var(--primary-color);
        }

        .text-input {
            border: 1px solid #ccc;
            padding: 4px;
            background: white;
            z-index: 1000;
            font-family: 'Comic Sans MS', sans-serif;
            font-size: 1rem;
        }

        .orientation-message {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.9);
            color: white;
            justify-content: center;
            align-items: center;
            text-align: center;
            font-size: 1.5rem;
            z-index: 9999;
        }

        @media (max-width: 768px) {
            .header {
                padding: 6px 12px;
            }

            .title {
                font-size: 1.2rem;
            }

            .toolbar {
                padding: 6px;
                gap: 6px;
            }

            .btn-tool {
                width: 40px;
                height: 40px;
                font-size: 0.9rem;
            }

            .btn-tool i {
                font-size: 1.2rem;
            }

            .color-picker {
                width: 32px;
                height: 32px;
            }

            .zoom-btn {
                width: 36px;
                height: 36px;
                font-size: 1rem;
            }

            input[type="range"] {
                width: 60px;
            }
        }

        @media (orientation: portrait) and (max-width: 768px) {
            .orientation-message {
                display: flex;
            }

            .canvas-container,
            .header,
            .toolbar {
                display: none;
            }
        }
    </style>
</head>

<body>
    <div class="orientation-message">
        请将设备旋转至横屏以使用绘画板
    </div>
    <div class="header">
        <div class="title">🎨 儿童绘画板</div>
        <div>
            <button id="undo-btn" class="btn btn-sm btn-light me-1">
                <i class="bi bi-arrow-left"></i>
            </button>
            <button id="redo-btn" class="btn btn-sm btn-light me-1">
                <i class="bi bi-arrow-right"></i>
            </button>
            <button id="replay-btn" class="btn btn-sm btn-light me-1">
                <i class="bi bi-play-fill"></i>
            </button>
            <button id="export-btn" class="btn btn-sm btn-success me-1">
                <i class="bi bi-download"></i>
            </button>
            <button id="clear-all-btn" class="btn btn-sm btn-danger">
                <i class="bi bi-trash"></i>
            </button>
        </div>
    </div>
    <div class="toolbar">
        <div class="btn-tool active" id="pen-tool" title="画笔 (P)">
            <i class="bi bi-pencil"></i>
            <span class="btn-tool-label">画笔</span>
        </div>
        <div class="btn-tool" id="eraser-tool" title="橡皮擦 (E)">
            <i class="bi bi-eraser"></i>
            <span class="btn-tool-label">橡皮</span>
        </div>
        <div class="btn-tool" id="fill-tool" title="填充 (F)">
            <i class="bi bi-paint-bucket"></i>
            <span class="btn-tool-label">填充</span>
        </div>
        <div class="btn-tool" id="text-tool" title="文本 (T)">
            <i class="bi bi-fonts"></i>
            <span class="btn-tool-label">文本</span>
        </div>
        <div class="btn-tool" id="color-picker-tool" title="颜色拾取器 (I)">
            <i class="bi bi-eyedropper"></i>
            <span class="btn-tool-label">拾色</span>
        </div>
        <div class="btn-tool" id="symmetry-toggle" title="对称模式 (M)">
            <i class="bi bi-symmetry-horizontal"></i>
            <span class="btn-tool-label">对称</span>
        </div>
        <div class="btn-group" role="group" id="shape-tools" aria-label="Shape Tools">
            <button type="button" class="btn btn-tool" id="shape-line" title="直线 (L)">
                <i class="bi bi-slash"></i>
                <span class="btn-tool-label">直线</span>
            </button>
            <button type="button" class="btn btn-tool" id="line-style-tool" title="线条样式 (D)">
                <i class="bi bi-dash"></i>
                <span class="btn-tool-label">线条</span>
            </button>
            <button type="button" class="btn btn-tool" id="shape-rect" title="矩形 (R)">
                <i class="bi bi-square"></i>
                <span class="btn-tool-label">矩形</span>
            </button>
            <button type="button" class="btn btn-tool" id="shape-circle" title="圆形 (C)">
                <i class="bi bi-circle"></i>
                <span class="btn-tool-label">圆形</span>
            </button>
            <button type="button" class="btn btn-tool" id="shape-triangle" title="三角形 (G)">
                <i class="bi bi-triangle"></i>
                <span class="btn-tool-label">三角</span>
            </button>
            <button type="button" class="btn btn-tool" id="shape-pentagon" title="五边形 (N)">
                <i class="bi bi-pentagon"></i>
                <span class="btn-tool-label">五边</span>
            </button>
            <button type="button" class="btn btn-tool" id="shape-hexagon" title="六边形 (H)">
                <i class="bi bi-hexagon"></i>
                <span class="btn-tool-label">六边</span>
            </button>
            <button type="button" class="btn btn-tool" id="shape-star" title="星星 (S)">
                <i class="bi bi-star"></i>
                <span class="btn-tool-label">星星</span>
            </button>
            <button type="button" class="btn btn-tool" id="shape-heart" title="心形 (A)">
                <i class="bi bi-heart"></i>
                <span class="btn-tool-label">心形</span>
            </button>
        </div>
        <div class="btn-tool" id="stamp-tool" title="图章 (B)">
            <i class="bi bi-star"></i>
            <span class="btn-tool-label">图章</span>
        </div>
        <div class="btn-tool" id="fill-shape-toggle" title="填充形状 (O)">
            <i class="bi bi-square-fill"></i>
            <span class="btn-tool-label">填充</span>
        </div>
        <div class="brush-size-control">
            <div class="brush-size-preview" id="brush-preview"></div>
            <input type="range" id="brush-size" min="1" max="50" value="5">
        </div>
        <div class="color-palette">
            <div class="color-picker active" style="background-color: #000000;" data-color="#000000"></div>
            <div class="color-picker" style="background-color: #ff0000;" data-color="#ff0000"></div>
            <div class="color-picker" style="background-color: #ff9900;" data-color="#ff9900"></div>
            <div class="color-picker" style="background-color: #ffff00;" data-color="#ffff00"></div>
            <div class="color-picker" style="background-color: #00ff00;" data-color="#00ff00"></div>
            <div class="color-picker" style="background-color: #0099ff;" data-color="#0099ff"></div>
            <div class="color-picker" style="background-color: #9900ff;" data-color="#9900ff"></div>
            <div class="color-picker" style="background-color: #ff00ff;" data-color="#ff00ff"></div>
            <div class="color-picker" style="background-color: #ffffff; border: 1px solid #ddd;" data-color="#ffffff">
            </div>
            <input type="color" id="custom-color" value="#ff0000" style="opacity: 0; width: 0; height: 0;">
            <button id="custom-color-btn" class="btn btn-sm" style="background-color: #f8f9fa;">
                <i class="bi bi-palette"></i>
            </button>
        </div>
    </div>
    <div class="canvas-container">
        <canvas id="drawing-canvas"></canvas>
        <canvas id="preview-canvas"></canvas>
        <div class="zoom-controls">
            <button class="zoom-btn" id="zoom-in">
                <i class="bi bi-plus-lg"></i>
            </button>
            <button class="zoom-btn" id="zoom-out">
                <i class="bi bi-dash-lg"></i>
            </button>
            <button class="zoom-btn" id="zoom-reset">
                <i class="bi bi-arrow-counterclockwise"></i>
            </button>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <noscript>
        <style>
            body {
                display: none !important;
            }
        </style>
        <meta http-equiv="refresh" content="0; url=about:blank">
    </noscript>
    <script src="security.js"></script>
    <script>
        $(document).ready(function () {
            const canvas = document.getElementById('drawing-canvas');
            const ctx = canvas.getContext('2d');
            const previewCanvas = document.getElementById('preview-canvas');
            const previewCtx = previewCanvas.getContext('2d');
            const drawingState = {
                isDrawing: false,
                lastX: 0,
                lastY: 0,
                currentTool: 'pen',
                currentColor: '#000000',
                brushSize: 5,
                scale: 1,
                offsetX: 0,
                offsetY: 0,
                isPanning: false,
                startPanX: 0,
                startPanY: 0,
                drawingHistory: [],
                historyIndex: -1,
                lineStyle: 'solid',
                fillShapes: false,
                backgroundColor: '#ffffff',
                symmetryMode: false,
                pinchStartDistance: 0,
                pinchStartScale: 1
            };
            let currentShape = 'rect';
            let startX, startY;

            // Lock orientation to landscape on mobile
            function lockOrientation() {
                if (screen.orientation && screen.orientation.lock) {
                    screen.orientation.lock('landscape').catch(err => {
                        console.warn('Orientation lock failed:', err);
                    });
                }
            }

            // Enter full-screen mode on mobile
            function enterFullScreen() {
                if (/Mobi|Android/i.test(navigator.userAgent) && !document.fullscreenElement) {
                    document.documentElement.requestFullscreen().catch(err => {
                        console.warn('Full-screen failed:', err);
                    });
                }
            }

            // Initialize orientation and full-screen
            lockOrientation();
            enterFullScreen();

            // Handle orientation changes
            window.addEventListener('orientationchange', () => {
                lockOrientation();
                setTimeout(resizeCanvas, 100); // Delay to ensure orientation change completes
            });

            function resizeCanvas() {
                const container = $('.canvas-container');
                const width = window.innerWidth;
                const height = window.innerHeight - $('.header').outerHeight() - $('.toolbar').outerHeight();
                canvas.width = width * window.devicePixelRatio;
                canvas.height = height * window.devicePixelRatio;
                previewCanvas.width = canvas.width;
                previewCanvas.height = canvas.height;
                canvas.style.width = width + 'px';
                canvas.style.height = height + 'px';
                previewCanvas.style.width = width + 'px';
                previewCanvas.style.height = height + 'px';
                ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
                centerCanvas();
                redrawCanvas();
            }

            $(window).resize(resizeCanvas);

            function centerCanvas() {
                const container = $('.canvas-container');
                drawingState.offsetX = (container.width() - canvas.width / window.devicePixelRatio * drawingState.scale) / 2;
                drawingState.offsetY = (container.height() - canvas.height / window.devicePixelRatio * drawingState.scale) / 2;
                applyTransform();
            }

            function saveDrawingState() {
                if (drawingState.historyIndex < drawingState.drawingHistory.length - 1) {
                    drawingState.drawingHistory = drawingState.drawingHistory.slice(0, drawingState.historyIndex + 1);
                }
                const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                drawingState.drawingHistory.push(imageData);
                drawingState.historyIndex++;
            }

            function redrawCanvas() {
                ctx.fillStyle = drawingState.backgroundColor;
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                if (drawingState.historyIndex >= 0 && drawingState.drawingHistory[drawingState.historyIndex]) {
                    ctx.putImageData(drawingState.drawingHistory[drawingState.historyIndex], 0, 0);
                }
            }

            function updateBrushPreview() {
                const preview = $('#brush-preview');
                preview.css({
                    'width': drawingState.brushSize + 'px',
                    'height': drawingState.brushSize + 'px',
                    'background-color': drawingState.currentColor
                });
            }

            function getCanvasPosition(e) {
                const rect = canvas.getBoundingClientRect();
                let clientX, clientY;
                if (e.touches) {
                    clientX = e.touches[0].clientX;
                    clientY = e.touches[0].clientY;
                } else {
                    clientX = e.clientX;
                    clientY = e.clientY;
                }
                const scaleX = canvas.width / rect.width;
                const scaleY = canvas.height / rect.height;
                return {
                    x: (clientX - rect.left - drawingState.offsetX) * scaleX / drawingState.scale,
                    y: (clientY - rect.top - drawingState.offsetY) * scaleY / drawingState.scale
                };
            }

            function updateCursor() {
                if (drawingState.currentTool === 'pen' || drawingState.currentTool === 'text' || drawingState.currentTool === 'colorPicker') {
                    canvas.style.cursor = `url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><circle cx="8" cy="8" r="${drawingState.brushSize / (2 * drawingState.scale)}" fill="${drawingState.currentColor}" stroke="black" stroke-width="1"/></svg>') ${drawingState.brushSize / (2 * drawingState.scale)} ${drawingState.brushSize / (2 * drawingState.scale)}, crosshair`;
                } else if (drawingState.currentTool === 'eraser') {
                    canvas.style.cursor = `url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><circle cx="8" cy="8" r="${drawingState.brushSize / (2 * drawingState.scale)}" fill="white" stroke="black" stroke-width="1"/></svg>') ${drawingState.brushSize / (2 * drawingState.scale)} ${drawingState.brushSize / (2 * drawingState.scale)}, crosshair`;
                } else if (drawingState.currentTool === 'fill') {
                    canvas.style.cursor = `url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path d="M8 1l2 2h3v3l2 2-2 2v3h-3l-2 2-2-2h-3v-3l-2-2 2-2v-3h3z" fill="${drawingState.currentColor}"/></svg>') 8 8, crosshair`;
                } else if (drawingState.currentTool === 'shape' || drawingState.currentTool === 'stamp') {
                    canvas.style.cursor = 'crosshair';
                }
            }

            $('.btn-tool').click(function () {
                const toolId = $(this).attr('id');
                if (toolId === 'symmetry-toggle') {
                    drawingState.symmetryMode = !drawingState.symmetryMode;
                    $(this).toggleClass('active', drawingState.symmetryMode);
                    return;
                }
                if (toolId === 'fill-shape-toggle') {
                    drawingState.fillShapes = !drawingState.fillShapes;
                    $(this).find('i').toggleClass('bi-square-fill bi-square');
                    return;
                }
                $('.btn-tool').not('#symmetry-toggle, #fill-shape-toggle').removeClass('active');
                $(this).addClass('active');
                switch (toolId) {
                    case 'pen-tool':
                        drawingState.currentTool = 'pen';
                        break;
                    case 'eraser-tool':
                        drawingState.currentTool = 'eraser';
                        drawingState.brushSize = drawingState.brushSize * 2;
                        $('#brush-size').val(drawingState.brushSize);
                        break;
                    case 'fill-tool':
                        drawingState.currentTool = 'fill';
                        break;
                    case 'text-tool':
                        drawingState.currentTool = 'text';
                        break;
                    case 'color-picker-tool':
                        drawingState.currentTool = 'colorPicker';
                        break;
                    case 'shape-line':
                    case 'shape-rect':
                    case 'shape-circle':
                    case 'shape-triangle':
                    case 'shape-pentagon':
                    case 'shape-hexagon':
                    case 'shape-star':
                    case 'shape-heart':
                        drawingState.currentTool = 'shape';
                        currentShape = toolId.replace('shape-', '');
                        break;
                    case 'stamp-tool':
                        drawingState.currentTool = 'stamp';
                        break;
                    case 'line-style-tool':
                        drawingState.lineStyle = drawingState.lineStyle === 'solid' ? 'dashed' : 'solid';
                        $(this).find('i').toggleClass('bi-dash bi-slash-lg');
                        break;
                }
                updateBrushPreview();
                updateCursor();
            });

            $('.color-picker').click(function () {
                $('.color-picker').removeClass('active');
                $(this).addClass('active');
                drawingState.currentColor = $(this).data('color');
                updateBrushPreview();
                updateCursor();
            });

            $('#custom-color-btn').click(function () {
                $('#custom-color').click();
            });

            $('#custom-color').change(function () {
                const color = $(this).val();
                drawingState.currentColor = color;
                updateBrushPreview();
                updateCursor();
            });

            $('#brush-size').on('input', function () {
                drawingState.brushSize = parseInt($(this).val());
                updateBrushPreview();
                updateCursor();
            });

            $('#clear-all-btn').click(function () {
                if (confirm('确定要清空画布吗？')) {
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    ctx.fillStyle = drawingState.backgroundColor;
                    ctx.fillRect(0, 0, canvas.width, canvas.height);
                    drawingState.drawingHistory = [];
                    drawingState.historyIndex = -1;
                    saveDrawingState();
                }
            });

            $('#undo-btn').click(function () {
                if (drawingState.historyIndex > 0) {
                    drawingState.historyIndex--;
                    redrawCanvas();
                }
            });

            $('#redo-btn').click(function () {
                if (drawingState.historyIndex < drawingState.drawingHistory.length - 1) {
                    drawingState.historyIndex++;
                    redrawCanvas();
                }
            });

            $('#replay-btn').click(function () {
                let index = 0;
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.fillStyle = drawingState.backgroundColor;
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                function replayStep() {
                    if (index >= drawingState.drawingHistory.length) return;
                    ctx.putImageData(drawingState.drawingHistory[index], 0, 0);
                    index++;
                    setTimeout(replayStep, 500);
                }
                replayStep();
            });

            $('#export-btn').click(function () {
                const link = document.createElement('a');
                link.download = 'drawing.png';
                link.href = canvas.toDataURL('image/png');
                link.click();
            });

            $('#zoom-in').click(function () {
                drawingState.scale *= 1.2;
                centerCanvas();
                updateCursor();
            });

            $('#zoom-out').click(function () {
                drawingState.scale /= 1.2;
                centerCanvas();
                updateCursor();
            });

            $('#zoom-reset').click(function () {
                drawingState.scale = 1;
                drawingState.offsetX = 0;
                drawingState.offsetY = 0;
                centerCanvas();
                updateCursor();
            });

            function applyTransform() {
                canvas.style.transform = `translate(${drawingState.offsetX}px, ${drawingState.offsetY}px) scale(${drawingState.scale})`;
                previewCanvas.style.transform = canvas.style.transform;
            }

            function handleTextInput(e) {
                if (drawingState.currentTool !== 'text') return;
                e.preventDefault();
                e.stopPropagation();
                const pos = getCanvasPosition(e);
                const rect = canvas.getBoundingClientRect();
                $('.text-input').remove();
                const input = $('<input type="text" class="text-input">').css({
                    position: 'absolute',
                    left: (rect.left + drawingState.offsetX + pos.x * drawingState.scale) + 'px',
                    top: (rect.top + drawingState.offsetY + pos.y * drawingState.scale) + 'px',
                    font: '16px Comic Sans MS',
                    color: drawingState.currentColor,
                    border: '1px solid #ccc',
                    padding: '4px',
                    transform: `scale(${1 / drawingState.scale})`,
                    transformOrigin: 'top left',
                    zIndex: 9999,
                    minWidth: '80px'
                });
                $('body').append(input);
                input.focus();
                function commitText() {
                    const text = input.val();
                    if (text) {
                        ctx.save();
                        ctx.font = '16px Comic Sans MS';
                        ctx.fillStyle = drawingState.currentColor;
                        ctx.fillText(text, pos.x, pos.y + 16);
                        ctx.restore();
                        saveDrawingState();
                    }
                    input.remove();
                }
                input.on('keydown', function (event) {
                    if (event.key === 'Enter') {
                        commitText();
                        return false;
                    }
                });
                input.on('blur', commitText);
                input.on('mousedown touchstart', function (e) {
                    e.stopPropagation();
                });
            }

            function handleColorPicker(e) {
                if (drawingState.currentTool !== 'colorPicker') return;
                const pos = getCanvasPosition(e);
                const pixel = ctx.getImageData(pos.x, pos.y, 1, 1).data;
                const color = `rgb(${pixel[0]},${pixel[1]},${pixel[2]})`;
                drawingState.currentColor = color;
                $('#custom-color').val(rgbToHex(pixel[0], pixel[1], pixel[2]));
                updateBrushPreview();
                updateCursor();
            }

            function rgbToHex(r, g, b) {
                return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1).toUpperCase();
            }

            function startDrawing(e) {
                if (e.type === 'mousedown' && (e.button === 1 || e.button === 2)) {
                    drawingState.isPanning = true;
                    drawingState.startPanX = e.clientX - drawingState.offsetX;
                    drawingState.startPanY = e.clientY - drawingState.offsetY;
                    canvas.style.cursor = 'grabbing';
                    e.preventDefault();
                    return;
                }
                if (e.type === 'mousedown' && e.button !== 0) return;
                const pos = getCanvasPosition(e);
                drawingState.isDrawing = true;
                drawingState.lastX = pos.x;
                drawingState.lastY = pos.y;
                startX = pos.x;
                startY = pos.y;
                if (drawingState.currentTool === 'text') {
                    handleTextInput(e);
                    drawingState.isDrawing = false;
                    return;
                }
                if (drawingState.currentTool === 'colorPicker') {
                    handleColorPicker(e);
                    drawingState.isDrawing = false;
                    return;
                }
                if (drawingState.currentTool === 'fill') {
                    floodFill(pos.x, pos.y);
                    drawingState.isDrawing = false;
                    return;
                }
                if (drawingState.currentTool === 'stamp') {
                    drawStamp(pos.x, pos.y);
                    drawingState.isDrawing = false;
                    saveDrawingState();
                    return;
                }
                if (drawingState.currentTool === 'shape') {
                    return;
                }
                ctx.beginPath();
                ctx.moveTo(drawingState.lastX, drawingState.lastY);
            }

            function draw(e) {
                const pos = getCanvasPosition(e);
                if (drawingState.isPanning) {
                    drawingState.offsetX = e.clientX - drawingState.startPanX;
                    drawingState.offsetY = e.clientY - drawingState.startPanY;
                    applyTransform();
                    return;
                }
                if (!drawingState.isDrawing) return;
                if (drawingState.currentTool === 'shape') {
                    previewCtx.clearRect(0, 0, previewCanvas.width, previewCanvas.height);
                    drawShape(previewCtx, startX, startY, pos.x, pos.y, true);
                    return;
                }
                if (drawingState.currentTool === 'pen') {
                    ctx.beginPath();
                    ctx.moveTo(drawingState.lastX, drawingState.lastY);
                    ctx.lineTo(pos.x, pos.y);
                    ctx.strokeStyle = drawingState.currentColor;
                    ctx.lineWidth = drawingState.brushSize;
                    ctx.lineCap = 'round';
                    ctx.lineJoin = 'round';
                    if (drawingState.lineStyle === 'dashed') {
                        ctx.setLineDash([10, 10]);
                    } else {
                        ctx.setLineDash([]);
                    }
                    ctx.stroke();
                    if (drawingState.symmetryMode) {
                        ctx.beginPath();
                        ctx.moveTo(canvas.width - drawingState.lastX, drawingState.lastY);
                        ctx.lineTo(canvas.width - pos.x, pos.y);
                        ctx.stroke();
                    }
                } else if (drawingState.currentTool === 'eraser') {
                    ctx.beginPath();
                    ctx.moveTo(drawingState.lastX, drawingState.lastY);
                    ctx.lineTo(pos.x, pos.y);
                    ctx.strokeStyle = drawingState.backgroundColor;
                    ctx.lineWidth = drawingState.brushSize;
                    ctx.lineCap = 'round';
                    ctx.lineJoin = 'round';
                    ctx.stroke();
                }
                drawingState.lastX = pos.x;
                drawingState.lastY = pos.y;
            }

            function endDrawing(e) {
                if (drawingState.isPanning) {
                    drawingState.isPanning = false;
                    canvas.style.cursor = '';
                    $('.btn-tool.active').trigger('click');
                    return;
                }
                if (!drawingState.isDrawing) return;
                const pos = getCanvasPosition(e);
                previewCtx.clearRect(0, 0, previewCanvas.width, previewCanvas.height);
                if (drawingState.currentTool === 'shape') {
                    drawShape(ctx, startX, startY, pos.x, pos.y, false);
                }
                drawingState.isDrawing = false;
                ctx.setLineDash([]);
                saveDrawingState();
            }

            function drawShape(ctx, x1, y1, x2, y2, isPreview) {
                ctx.fillStyle = isPreview ? 'rgba(78, 115, 223, 0.3)' : drawingState.currentColor;
                ctx.strokeStyle = isPreview ? 'rgba(78, 115, 223, 0.7)' : drawingState.currentColor;
                ctx.lineWidth = drawingState.brushSize;
                if (drawingState.lineStyle === 'dashed' && !isPreview) {
                    ctx.setLineDash([10, 10]);
                } else {
                    ctx.setLineDash([]);
                }
                ctx.beginPath();
                switch (currentShape) {
                    case 'line':
                        ctx.moveTo(x1, y1);
                        ctx.lineTo(x2, y2);
                        break;
                    case 'rect':
                        ctx.rect(x1, y1, x2 - x1, y2 - y1);
                        break;
                    case 'circle':
                        const radius = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
                        ctx.arc(x1, y1, radius, 0, Math.PI * 2);
                        break;
                    case 'triangle':
                        drawPolygon(ctx, x1, y1, x2, y2, 3);
                        break;
                    case 'pentagon':
                        drawPolygon(ctx, x1, y1, x2, y2, 5);
                        break;
                    case 'hexagon':
                        drawPolygon(ctx, x1, y1, x2, y2, 6);
                        break;
                    case 'star':
                        drawStar(ctx, x1, y1, Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)), 5);
                        break;
                    case 'heart':
                        drawHeart(ctx, x1, y1, x2 - x1, y2 - y1);
                        break;
                }
                ctx.stroke();
                if (drawingState.fillShapes && !isPreview) {
                    ctx.fill();
                }
                if (drawingState.symmetryMode && !isPreview) {
                    ctx.beginPath();
                    switch (currentShape) {
                        case 'line':
                            ctx.moveTo(canvas.width - x1, y1);
                            ctx.lineTo(canvas.width - x2, y2);
                            break;
                        case 'rect':
                            ctx.rect(canvas.width - x1 - (x2 - x1), y1, x2 - x1, y2 - y1);
                            break;
                        case 'circle':
                            const radius = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
                            ctx.arc(canvas.width - x1, y1, radius, 0, Math.PI * 2);
                            break;
                        case 'triangle':
                            drawPolygon(ctx, canvas.width - x1, y1, canvas.width - x2, y2, 3);
                            break;
                        case 'pentagon':
                            drawPolygon(ctx, canvas.width - x1, y1, canvas.width - x2, y2, 5);
                            break;
                        case 'hexagon':
                            drawPolygon(ctx, canvas.width - x1, y1, canvas.width - x2, y2, 6);
                            break;
                        case 'star':
                            drawStar(ctx, canvas.width - x1, y1, Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)), 5);
                            break;
                        case 'heart':
                            drawHeart(ctx, canvas.width - x1, y1, x2 - x1, y2 - y1);
                            break;
                    }
                    ctx.stroke();
                    if (drawingState.fillShapes) {
                        ctx.fill();
                    }
                }
            }

            function drawPolygon(ctx, x1, y1, x2, y2, sides) {
                const radius = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
                const centerX = x1;
                const centerY = y1;
                ctx.beginPath();
                for (let i = 0; i < sides; i++) {
                    const angle = (Math.PI * 2 / sides) * i - Math.PI / 2;
                    const x = centerX + radius * Math.cos(angle);
                    const y = centerY + radius * Math.sin(angle);
                    if (i === 0) {
                        ctx.moveTo(x, y);
                    } else {
                        ctx.lineTo(x, y);
                    }
                }
                ctx.closePath();
            }

            function drawStar(ctx, x, y, radius, points) {
                ctx.beginPath();
                const angle = Math.PI / points;
                for (let i = 0; i < 2 * points; i++) {
                    const r = i % 2 === 0 ? radius : radius / 2;
                    const a = i * angle - Math.PI / 2;
                    ctx.lineTo(x + r * Math.cos(a), y + r * Math.sin(a));
                }
                ctx.closePath();
            }

            function drawHeart(ctx, x, y, width, height) {
                ctx.beginPath();
                const scale = width / 50;
                const h = height / width;
                const cx = x + width / 2;
                const cy = y + height / 2;
                ctx.moveTo(cx, cy + 15 * scale * h);
                ctx.bezierCurveTo(cx - 7 * scale, cy + 15 * scale * h,
                    cx - 15 * scale, cy + 5 * scale * h,
                    cx - 15 * scale, cy - 5 * scale * h);
                ctx.bezierCurveTo(cx - 15 * scale, cy - 15 * scale * h,
                    cx - 5 * scale, cy - 15 * scale * h,
                    cx, cy - 5 * scale * h);
                ctx.bezierCurveTo(cx + 5 * scale, cy - 15 * scale * h,
                    cx + 15 * scale, cy - 15 * scale * h,
                    cx + 15 * scale, cy - 5 * scale * h);
                ctx.bezierCurveTo(cx + 15 * scale, cy + 5 * scale * h,
                    cx + 7 * scale, cy + 15 * scale * h,
                    cx, cy + 15 * scale * h);
                ctx.closePath();
            }

            function drawStamp(x, y) {
                ctx.save();
                ctx.fillStyle = drawingState.currentColor;
                ctx.strokeStyle = drawingState.currentColor;
                ctx.lineWidth = 2;
                const size = drawingState.brushSize * 3;
                drawStar(ctx, x, y, size / 2, 5);
                ctx.fill();
                ctx.stroke();
                if (drawingState.symmetryMode) {
                    drawStar(ctx, canvas.width - x, y, size / 2, 5);
                    ctx.fill();
                    ctx.stroke();
                }
                ctx.restore();
            }

            function floodFill(startX, startY) {
                const pixelData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                const startPos = (Math.floor(startY) * canvas.width + Math.floor(startX)) * 4;
                const targetColor = {
                    r: pixelData.data[startPos],
                    g: pixelData.data[startPos + 1],
                    b: pixelData.data[startPos + 2],
                    a: pixelData.data[startPos + 3]
                };
                const fillColor = hexToRgb(drawingState.currentColor);
                if (colorsMatch(targetColor, fillColor)) return;
                const tempCanvas = document.createElement('canvas');
                tempCanvas.width = canvas.width;
                tempCanvas.height = canvas.height;
                const tempCtx = tempCanvas.getContext('2d');
                tempCtx.putImageData(pixelData, 0, 0);
                fill(tempCtx, Math.floor(startX), Math.floor(startY), targetColor, fillColor);
                ctx.drawImage(tempCanvas, 0, 0);
                saveDrawingState();
            }

            function fill(ctx, x, y, targetColor, fillColor) {
                const stack = [[x, y]];
                const width = ctx.canvas.width;
                const height = ctx.canvas.height;
                const imageData = ctx.getImageData(0, 0, width, height);
                const data = imageData.data;
                while (stack.length) {
                    const [x, y] = stack.pop();
                    const pos = (y * width + x) * 4;
                    if (x < 0 || x >= width || y < 0 || y >= height) continue;
                    if (!colorsMatch({
                        r: data[pos],
                        g: data[pos + 1],
                        b: data[pos + 2],
                        a: data[pos + 3]
                    }, targetColor)) continue;
                    data[pos] = fillColor.r;
                    data[pos + 1] = fillColor.g;
                    data[pos + 2] = fillColor.b;
                    data[pos + 3] = fillColor.a;
                    stack.push([x + 1, y]);
                    stack.push([x - 1, y]);
                    stack.push([x, y + 1]);
                    stack.push([x, y - 1]);
                }
                ctx.putImageData(imageData, 0, 0);
            }

            function colorsMatch(c1, c2) {
                return c1.r === c2.r && c1.g === c2.g && c1.b === c2.b && c1.a === c2.a;
            }

            function hexToRgb(hex) {
                hex = hex.replace('#', '');
                const r = parseInt(hex.substring(0, 2), 16);
                const g = parseInt(hex.substring(2, 4), 16);
                const b = parseInt(hex.substring(4, 6), 16);
                return { r, g, b, a: 255 };
            }

            // Handle pinch-to-zoom
            function getPinchDistance(touches) {
                const dx = touches[0].clientX - touches[1].clientX;
                const dy = touches[0].clientY - touches[1].clientY;
                return Math.sqrt(dx * dx + dy * dy);
            }

            canvas.addEventListener('touchstart', function (e) {
                e.preventDefault();
                if (e.touches.length === 1) {
                    const touch = e.touches[0];
                    const mouseEvent = new MouseEvent('mousedown', {
                        clientX: touch.clientX,
                        clientY: touch.clientY
                    });
                    canvas.dispatchEvent(mouseEvent);
                } else if (e.touches.length === 2) {
                    drawingState.pinchStartDistance = getPinchDistance(e.touches);
                    drawingState.pinchStartScale = drawingState.scale;
                    drawingState.isDrawing = false;
                }
            });

            canvas.addEventListener('touchmove', function (e) {
                e.preventDefault();
                if (e.touches.length === 1) {
                    const touch = e.touches[0];
                    const mouseEvent = new MouseEvent('mousemove', {
                        clientX: touch.clientX,
                        clientY: touch.clientY
                    });
                    canvas.dispatchEvent(mouseEvent);
                } else if (e.touches.length === 2) {
                    const distance = getPinchDistance(e.touches);
                    const scaleFactor = distance / drawingState.pinchStartDistance;
                    drawingState.scale = drawingState.pinchStartScale * scaleFactor;
                    centerCanvas();
                    updateCursor();
                }
            });

            canvas.addEventListener('touchend', function (e) {
                e.preventDefault();
                if (e.touches.length < 2) {
                    const mouseEvent = new MouseEvent('mouseup');
                    canvas.dispatchEvent(mouseEvent);
                }
            });

            canvas.addEventListener('mousedown', startDrawing);
            canvas.addEventListener('mousemove', draw);
            canvas.addEventListener('mouseup', endDrawing);
            canvas.addEventListener('mouseleave', endDrawing);
            canvas.addEventListener('contextmenu', function (e) {
                e.preventDefault();
            });

            $(document).on('keydown', function (e) {
                switch (e.key.toLowerCase()) {
                    case 'p':
                        $('#pen-tool').click();
                        break;
                    case 'e':
                        $('#eraser-tool').click();
                        break;
                    case 'f':
                        $('#fill-tool').click();
                        break;
                    case 't':
                        $('#text-tool').click();
                        break;
                    case 'i':
                        $('#color-picker-tool').click();
                        break;
                    case 'm':
                        $('#symmetry-toggle').click();
                        break;
                    case 'l':
                        $('#shape-line').click();
                        break;
                    case 'r':
                        $('#shape-rect').click();
                        break;
                    case 'c':
                        $('#shape-circle').click();
                        break;
                    case 'g':
                        $('#shape-triangle').click();
                        break;
                    case 'n':
                        $('#shape-pentagon').click();
                        break;
                    case 'h':
                        $('#shape-hexagon').click();
                        break;
                    case 's':
                        $('#shape-star').click();
                        break;
                    case 'a':
                        $('#shape-heart').click();
                        break;
                    case 'b':
                        $('#stamp-tool').click();
                        break;
                    case 'o':
                        $('#fill-shape-toggle').click();
                        break;
                    case 'd':
                        $('#line-style-tool').click();
                        break;
                    case 'z':
                        if (e.ctrlKey || e.metaKey) {
                            $('#undo-btn').click();
                            e.preventDefault();
                        }
                        break;
                    case 'y':
                        if (e.ctrlKey || e.metaKey) {
                            $('#redo-btn').click();
                            e.preventDefault();
                        }
                        break;
                }
            });

            // Initialize canvas
            resizeCanvas();
            ctx.fillStyle = drawingState.backgroundColor;
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            saveDrawingState();
            updateBrushPreview();
        });
    </script>
</body>

</html>